var cookie_key = '_last_course_catalog_key_';
$(function () {

    autoSign();

    //登录个人中心，自动签到
    function autoSign() {
        var obj = getData(null, null);
        var isSign = obj.isSign;
        if (!isSign) {
            setTimeout(function () {
                saveSignIn();
            }, 1000);
        }
    }

    $('body').on('click', '#order-status a', function () {
        $(this).addClass('c-info').siblings().removeClass('c-info').addClass('c-999');
        queryMyCourseData(1);
        var noData = $('section.no-data__wrap')
        if (noData) {
            var text = $(this).text()
            if (text == '全部') {
                text = '';
            }
            $(noData).find('p span').text('没有查询到任何' + text + '课程~~~');
        }
    }).on('click', '.close', function () {
        var _div = $(this).parent('div');
        _div.addClass("hide");
        var key = $(_div).data('key');
        SetCookie(cookie_key, key);
    }).on('click', '.checkPlay', function () {
        var _this = $(this);
        var couId = $(_this).data("id");
        sysCheckFn(_this, '', 2, couId);
    }).on('click', '.continue', function () {
        var _this = $(this);
        var couId = $(_this).data("id");
        var catalogid = $(_this).data("catalogid");
        sysCheckFn(_this, '', 3, couId + '|' + catalogid);
    });
    //获取最后播放的一个目录
    getUserLastStudyCourseCatalog();

    //基本学习统计
    userStudyBaseStatistics();

    //套餐课程选择
    /* packCourseFn()*/
    //我的课程
    queryMyCourseData(1);

    /*$('.u-my-course_box').slimScroll({
        height: '100%',
        railOpacity: 0.9,
        alwaysVisible: true
    });*/

    // 门课程在学中
    getUserCourseNum();

    /**
     *  我学习的 1/8 门课程在学中
     */
    function getUserCourseNum() {
        $.ajax({
            url: baseloaction + '/web/uc/course/getUserCourseNum',
            type: 'post',
            dataType: 'json',
            success: function (result) {
                if (result.success == true) {
                    if (result.entity.buyCourseNum == 0) {
                        $("#user-course-num").text('0');
                    } else {
                        $("#user-course-num").text(result.entity.buyCourseNum);
                    }
                }
            }
        });
    }
});

/**
 * 获取最后播放的一个目录
 */
function getUserLastStudyCourseCatalog() {
    setTimeout(function () {
        $.ajax({
            url: baseloaction + '/web/uc/course/getUserLastStudyCourseCatalog',
            type: 'post',
            dataType: 'json',
            success: function (result) {
                if (result.success == true) {
                    var playRecord = result.entity;
                    if (playRecord != null) {
                        var courseCatalog = playRecord.courseCatalog;
                        var course = playRecord.buyCourse;
                        var cookieVal = playRecord.buyCourseId + '-' + playRecord.courseId + '-' + playRecord.catalogId;
                        var _val = getCookie(cookie_key);
                        if (_val != cookieVal) {
                            $("#last-study-catalog-box").removeClass("hide");
                        }
                        $("#lastStudyText").text('上次学到：' + course.courseName + '/' + courseCatalog.catalogName);
                        if (course.courseTypeKey == 'PACKAGE') {//套餐课程
                            // $("#lastStudyLink").attr("href", baseloaction + '/web/uc/play/toPlayCourse?packageId=' + playRecord.buyCourseId + '&courseId=' + playRecord.courseId + '&catalogId=' + playRecord.catalogId + '&type=LOBBY');
                            $("#lastStudyLink").attr("href","javascript:void(0)");
                            $("#lastStudyLink").attr("onclick", "sysCheckFn('', '', 4, "+"'"+playRecord.buyCourseId + '|' + playRecord.courseId + '|' + playRecord.catalogId+"'"+")");
                        } else {//非套餐课程
                            // $("#lastStudyLink").attr("href", baseloaction + '/web/uc/play/toPlayCourse?packageId=0&courseId=' + playRecord.courseId + '&catalogId=' + playRecord.catalogId + '&type=LOBBY');
                            $("#lastStudyLink").attr("href","javascript:void(0)");
                            $("#lastStudyLink").attr("onclick", "sysCheckFn('', '', 3, "+"'"+playRecord.courseId + '|' + playRecord.catalogId+"'"+")");
                            // sysCheckFn('', '', 3, playRecord.courseId+","+playRecord.catalogId);
                        }
                        $("#last-study-catalog-box").attr("data-key", cookieVal);
                    }
                }
            },
            error: function (error) {

            }
        })
    }, 450);
}

//套餐课程选择
var packCourseFn = function () {
    var _ele = $('#packCoursEle').val()
    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        area: ['880px', '580px'],
        shadeClose: false,
        skin: 'lay_ppComment__wrap',
        content: _ele,
        btn: ' 确定 ',
        yes: function (index, layero) {
            layer.close(index)
            //选择完成确定 回调
        }
    })
}

/**
 * 获取课程列表
 * @param pageNo 页码
 */
function queryMyCourseData(pageNo) {
    var courseType = $('#order-status>a.c-info').attr('name');
    var params = {'courseTypeKey': courseType};
    params = JSON.stringify(params);
    getPageAjaxData({
        url: baseloaction + '/web/uc/course/ajax/myCourseList',//请求URL
        contextId: 'course_list_context',//响应内容页面设置内容ID
        params: params,//请求参数
        pageNo: pageNo,//页码
        pageCall: queryMyCourseData, //分页回调加载数据(点击上下页时调用,该方法也在加载页面完成时调用)
        callback: function () {//数据加载完成回调
            lazyCourseImage();
            // tooltips hover
            $('[data-toggle=tooltip]').tooltip({
                container: "body",
                html: true
            })
        }
    });
}

/**
 * 基本学习统计
 */
function userStudyBaseStatistics() {
    setTimeout(function () {
        $.ajax({
            url: baseloaction + '/web/uc/course/userStudyBaseStatistics',
            type: 'post',
            dataType: 'json',
            success: function (result) {
                var entity = result.entity;
                var userObj = entity.user;
                //累计观看(分钟)
                var studyTotalTime = userObj.studyTotalTime;
                if (studyTotalTime == null) {
                    studyTotalTime = 0;
                }
                var m = 0;
                var h = 0;
                if (studyTotalTime > 0) {
                    studyTotalTime = parseInt(studyTotalTime / 60);
                    m = parseInt(studyTotalTime % 60);
                    h = (studyTotalTime - m) / 60;
                }
                var text = h + '时' + m + '分';
                setText('studyTotalTime', text, text);
                //参加直播场次(次)
                var joinLiveCount = userObj.joinLiveCount;
                if (joinLiveCount == null) {
                    joinLiveCount = 0;
                }
                setText('joinLiveCount', joinLiveCount, '参加直播场次:' + joinLiveCount + '次');
                //做题量(道)
                var questionNum = userObj.questionNum;
                if (questionNum == null) {
                    questionNum = 0;
                }
                setText('questionNum', questionNum, '做题量:' + questionNum + '道');
                //试卷(套)
                var examNum = userObj.examNum;
                if (examNum == null) {
                    examNum = 0;
                }
                setText('examNum', examNum, '试卷:' + examNum + '套');
                //总签到数(天)
                var signNum = userObj.signNum;
                if (signNum == null) {
                    signNum = 0;
                }
                setText('signNum', signNum, '总签到数:' + signNum + '天');
                var totalCount = parseInt(entity.examUserExpand.totalCount);
                var errorCount = parseInt(entity.examUserExpand.errorCount);
                if (entity.examUserExpand.totalCount == null || totalCount == 0) {
                    averagePrecision = 0;
                } else {
                    var _averagePrecision = parseFloat(totalCount - errorCount) / totalCount;
                    var averagePrecision = parseFloat(_averagePrecision * 100).toFixed(1);
                }
                setText('averagePrecision', averagePrecision, '正确率:' + averagePrecision + '%');
            }
        });
    });
}

/**
 * 设置内容显示
 * @param id 标签ID
 * @param num 数量
 * @param text title显示内容
 */
function setText(id, num, text) {
    $("#" + id).text(num);
    var em = $("#" + id).parent("div").parent('section');
    $(em).attr('data-original-title', text);
}